package com.ddzh.security;

import com.ddzh.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;

@Component
//登入成功后的返回
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	/**
	 * 回调函数，登录成功后的处理
	 * @param request
	 * @param response
	 * @param authentication 代表全局的身份信息
	 * @throws IOException
	 * @throws ServletException
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
		response.setContentType("application/json;charset=UTF-8");
		//获取登入账户信息，获取到用户名
		String username = getLoginName(authentication);
		String result = null;
		try {
			//统一返回响应数据格式，这个是json对象和我们的Result一样
			result = "{\n" +
					"\n" +
					"\"flag\":true,\n" +
					"\n" +
					"\"data\":\""+ JwtTokenUtil.createToken(username)+"\",\n" +//加密，防止加密失败
					"\n" +
					"\"message\":\"\"\n" +
					"\n" +
					"}";
			response.getWriter().write(result);//返回响应信息
		} catch (Exception e) {
			e.printStackTrace();
			result = "{\n" +
					"\n" +
					"\"flag\":true,\n" +
					"\n" +
					"\"data\":\"\",\n" +
					"\n" +
					"\"message\":\""+e.getMessage()+"\"\n" +
					"\n" +
					"}";
			response.getWriter().write(result);
		}
	}

	private String getLoginName(Authentication authentication) {
		String username = null;
		Object principal = authentication.getPrincipal();
		if (principal instanceof UserDetails) {//UserDetails：我们用户认证继承他
			username = ((UserDetails) principal).getUsername();
		} else if (principal instanceof Principal) {
			username = ((Principal) principal).getName();
		} else if (principal instanceof String) {
			username = (String) principal;
		}
		return username;
	}

}
